<template>
  <div class="page-main" v-title data-title="技术库">
    <home-nav :userData="userinfo"></home-nav>
    <user-select
      ref="userSelect"
      @setResult="setPushUserName"
      :origin-target-keys="pushUserOriginTargetKeys"
      :limit="5"
    />
    <user-select ref="auditUserSelect" @setResult="setAuditUser" :origin-target-keys="[form.auditUser]" :limit="1" />
    <div class="container">
      <div class="head-content">
        <span class="bold-font">工程技术库</span>
        <div class="btn-line">
          <a-button
            v-if="!editDisable || checkCurrentTask(['submit'])"
            @click="handleSave('save')"
            class="hte-btn add-btn"
            type="primary"
          >
            保存
          </a-button>
          <a-button
            v-if="!editDisable || checkCurrentTask(['submit'])"
            @click="handleSave('submit')"
            class="hte-btn add-btn"
            type="primary"
          >
            提交
          </a-button>
          <a-button
            v-if="checkCurrentTask(['submit']) || [0, 3].indexOf(form.status) > -1"
            @click="handleDele()"
            class="hte-btn add-btn"
            type="primary"
          >
            删除
          </a-button>
        </div>
      </div>
      <div class="content">
        <a-form-model ref="ruleForm" :rules="rules" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
          <section>
            <div class="section-header">
              <div style="float: left">
                基本信息
                <div class="mouldTips">
                  <img src="@/assets/icon_warning2.png" style="display: inline-block; margin-top: -3px" />
                  注意：工程技术库关键参数提交后不可修改，请谨慎操作
                </div>
              </div>
              <div style="float: right; margin-right: 20px">
                <a-button type="link" style="color: red" @click="showTechEngineeFlowTips">流程审批说明</a-button>
              </div>
            </div>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="是否有项目号">
                  <a-select style="width: 100%" v-model="form.hadCode" :disabled="editDisable">
                    <a-select-option v-for="d in dicts.flagDict" :value="d.code" :key="d.code"
                      >{{ d.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目号：">
                  <a-input-search
                    readOnly
                    :disabled="editDisable"
                    :placeholder="form.hadCode != '1' ? '自动生成' : '选择项目编号'"
                    v-model="form.code"
                    @search="openProjectSelector"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="技术名称：" ref="name" prop="name">
                  <a-input v-model="form.name" :maxLength="16" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="技术等级：" ref="techLevel" prop="techLevel">
                  <div style="display: flex">
                    <a-select v-model="form.techLevel">
                      <a-select-option v-for="d in dicts.levelDict" :value="d.code" :key="d.code"
                        >{{ d.name }}
                      </a-select-option>
                    </a-select>
                    <a-button type="link" @click="openTechDegreeTest">测评</a-button>
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="技术编号：">
                  <a-input disabled :value="form.fileCode ? form.fileCode : form.fileNoShow" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="关键字：" ref="keyWordArr" prop="keyWordArr">
                  <a-tree-select
                    v-model="form.keyWordArr"
                    style="width: 100%"
                    :tree-data="keyWordsNodesTree"
                    tree-checkable
                    @change="changeKeyWord"
                    :show-checked-strategy="SHOW_PARENT"
                    search-placeholder="点击选择关键字"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="技术应用领域：" ref="applicationArea" prop="applicationArea">
                  <a-textarea :auto-size="{ minRows: 2, maxRows: 6 }" :maxLength="200" v-model="form.applicationArea" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="技术特性：" ref="techParam" prop="techParam">
                  <a-textarea :auto-size="{ minRows: 2, maxRows: 6 }" v-model="form.techParam" :maxLength="500" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="技术应用效果：" ref="applicationEffect" prop="applicationEffect">
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    v-model="form.applicationEffect"
                    :maxLength="500"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="技术缺陷：" ref="techDefect" prop="techDefect">
                  <a-textarea :auto-size="{ minRows: 2, maxRows: 6 }" v-model="form.techDefect" :maxLength="500" />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="项目经理：" ref="publishUserName" prop="publishUserName">
                  <a-input v-model="form.publishUserName" @click="selectPushUser" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="文件形式：" ref="fileType" prop="fileType">
                  <a-select default-value="1" style="width: 100%" v-model="form.fileType">
                    <a-select-option v-for="d in fileTypeDic" :value="d.code" :key="d.code"
                      >{{ d.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="技术类别：" ref="techCategory" prop="techCategory">
                  <a-select default-value="1" style="width: 100%" v-model="form.techCategory">
                    <a-select-option v-for="d in techCategoryDic" :value="d.code" :key="d.code"
                      >{{ d.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="一期验收时间：">
                  <a-input disabled v-model="form.acceptanceTimeOne" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="二期验收时间：">
                  <a-input disabled v-model="form.acceptanceTimeTwo" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="查阅次数：">
                  <a-input disabled v-model="form.visitsNum" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="被引用次数：">
                  <a-input disabled v-model="form.timesNumber" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </section>

          <section v-if="form.id">
            <div class="section-header">技术知识产权-专利</div>
            <div class="section-table">
              <div class="table-operations">
                <a-button v-if="!editDisable" type="primary" @click="patentAdd"> 新增 </a-button>
                <a-button v-if="!editDisable" @click="patentRemove"> 删除 </a-button>
                <a-table
                  class="hte-table-content"
                  :columns="patent.columns"
                  :data-source="form.patentList"
                  :pagination="false"
                  size="middle"
                  rowKey="id"
                  :row-selection="{ selectedRowKeys: patent.selectedRowKeys, onChange: onPatentSelectChange }"
                  :key="patent.freshKey"
                >
                  <template slot="patentCode" slot-scope="text, record">
                    <a-input v-model="record.code" placeholder="32字以内" :maxLength="32" />
                  </template>
                  <template slot="patentName" slot-scope="text, record">
                    <a-input v-model="record.name" placeholder="32字以内" :maxLength="32" />
                  </template>
                  <template slot="patentAmount" slot-scope="text, record">
                    <a-input-number v-model="record.amount" :min="0" :max="1000000" />
                  </template>
                  <template slot="patentLink" slot-scope="text, record">
                    <a-input v-model="record.link" placeholder="125字以内" :maxLength="125" />
                  </template>
                </a-table>
              </div>
            </div>
          </section>

          <!-- <section v-if="form.fileCode">
            <div class="section-header">
              <div style="float: left">
                核心文件
                <div class="mouldTips">
                  <img src="@/assets/icon_warning2.png" style="display: inline-block; margin-top: -3px" />
                  注意：此处上传的是核心技术文件，上传完毕直接进入保密文件库。在海芯不提供阅读，需要预约申请后才能阅读。
                </div>
              </div>
            </div>

            <div class="section-table">
              <div style="display: flex">
                <a-upload
                  name="file"
                  :multiple="false"
                  :action="uploadAction"
                  :headers="uploadHeaders"
                  @change="handleChange"
                  :showUploadList="false"
                >
                  <a-button type="primary" v-if="!editDisable">上传</a-button>
                </a-upload>
                <a-button style="margin-left: 10px" @click="deleteCoreFile" v-if="!editDisable">删除</a-button>
              </div>
              <div>
                <a-table
                  class="hte-table-content"
                  :columns="coreFile.colums"
                  :data-source="coreFile.fileList"
                  :pagination="false"
                  size="middle"
                  rowKey="id"
                  :row-selection="{ selectedRowKeys: coreFile.selectedRowKeys, onChange: onCorefileSelectChange }"
                >
                </a-table>
              </div>
            </div>
          </section> -->

          <section v-if="form.id">
            <div class="section-header">
              技术文件
              <div class="mouldTips">
                <img src="@/assets/icon_warning2.png" style="display: inline-block; margin-top: -3px" />
                注意：此处上传的附件是技术文件，在海芯可以继续阅读。
              </div>
            </div>
            <div class="section-table">
              <div style="display: flex">
                <ht-upload
                  ref="otherFileUpload"
                  class="upload-demo"
                  dbKey="Trd"
                  :busField="otherFile.busField"
                  :busKey="form.id"
                  :busType="otherFile.busType"
                  ftpKey="ftp"
                  :showFileList="false"
                  :on-success="afterUpload"
                  v-model="otherFile.fileList"
                >
                  <el-button size="small" type="primary" style="font-size: 14px" v-if="!editDisable">上传</el-button>
                </ht-upload>
                <a-button
                  v-if="
                    form.auditUser == userinfo.info.username ||
                    form.createUserId == userinfo.info.username ||
                    checkCurrentUser() ||
                    filterHasPermission('PROJECT_TECH_ENGINEE_MANAGER')
                  "
                  @click="downloadOtherFile"
                  style="margin-left: 10px"
                >
                  下载
                </a-button>
                <a-button @click="deleteOtherFile" style="margin-left: 10px" v-if="!editDisable"> 删除 </a-button>
              </div>
              <div>
                <a-table
                  class="hte-table-content"
                  :columns="otherFile.colums"
                  :data-source="otherFileList"
                  :pagination="false"
                  size="middle"
                  rowKey="id"
                  :row-selection="{ selectedRowKeys: otherFile.selectedRowKeys, onChange: onOtherfileSelectChange }"
                >
                  <template slot="name" slot-scope="text, record">
                    <a @click="showAttach(record)">{{ record.name }}</a>
                  </template>
                </a-table>
              </div>
            </div>
          </section>

          <section v-if="form.processInstanceId">
            <div class="section-header">审核信息</div>
            <enginee-approval :id="form.id" :process-instance-id="form.processInstanceId" :message-id="messageId" />
          </section>
        </a-form-model>
      </div>
    </div>
    <TechDegreeTest ref="TechDegreeTest" @close="closeTechDegreeTest" />
    <TechEngineeFlowTips ref="TechEngineeFlowTips" />
    <projectSelector @close="closeProjectSelector" ref="projectSelector" />
  </div>
</template>
<script>
import { strNotNull, getParamValFromUrl } from '@/utils/common.js'
import { getAction, postAction, previewAttach } from '@/api/manage'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { TreeSelect } from 'ant-design-vue'
import { formatFileSize, endWith } from '@/utils/common.js'
import { Modal } from 'ant-design-vue'
import Vue from 'vue'
import '@/config/upload.install.js'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
import { FlowMixin } from '@/mixins/FlowMixin'
import {filterHasPermission} from '@/utils/hasPermission'
export default {
  mixins: [FlowMixin],
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    UserSelect: () => import('@/components/tools/UserSelect'),
    EngineeApproval: () => import('@/views/tech/approval'),
    TechDegreeTest: () => import('@/views/tech/techDegree/TechDegreeTest'),
    TechEngineeFlowTips: () => import('@/views/tech/techengineeedit/TechEngineeFlowTips'),
    projectSelector: () => import('@/views/projectBuild/projectSelector'),
  },
  data() {
    return {
      SHOW_PARENT,
      messageId: '',
      form: {
        busType: '',
        id: null,
        hadCode: '1',
        code: '',
        fileNo: null,
        fileNoShow: null,
        fileCode: null,
        name: '',
        techLevel: '',
        keyWordArr: null,
        keyWord: '',
        applicationArea: '',
        techParam: '',
        applicationEffect: '',
        techDefect: '',
        publishUserId: '',
        publishUserName: '',
        fileType: '',
        techCategory: '',
        acceptanceTimeOne: null,
        acceptanceTimeTwo: null,
        visitsNum: 0,
        timesNumber: 0,
        patentList: [],
        auditPass: true,
        auditOpinion: '',
        auditUser: '',
        techClass: '40',
        processInstanceId: '',
      },
      rules: {
        code: [
          // {
          //   required: true,
          //   message: '请输入项目号',
          //   trigger: 'blur',
          // },
          { min: 1, max: 18, message: '项目号不超过18个字', trigger: 'blur' },
        ],
        name: [
          {
            required: true,
            message: '请输入技术名称',
            trigger: 'blur',
          },
          { min: 1, max: 16, message: '技术名称不超过16个字', trigger: 'blur' },
        ],
        techLevel: [
          {
            required: true,
            message: '请选择技术等级',
            trigger: 'blur',
          },
        ],
        keyWordArr: [
          {
            required: true,
            message: '请选择关键字',
            trigger: 'blur',
          },
        ],
        applicationArea: [
          {
            required: true,
            message: '请输入技术应用领域',
            trigger: 'blur',
          },
          { min: 1, max: 500, message: '技术应用领域不超过500个字', trigger: 'blur' },
        ],
        techParam: [
          {
            required: true,
            message: '请输入技术特性',
            trigger: 'blur',
          },
          { min: 1, max: 500, message: '技术特性不超过500个字', trigger: 'blur' },
        ],
        applicationEffect: [
          {
            required: true,
            message: '请输入技术应用效果',
            trigger: 'blur',
          },
          { min: 1, max: 500, message: '技术应用效果不超过500个字', trigger: 'blur' },
        ],
        techDefect: [
          {
            required: true,
            message: '请输入技术缺陷',
            trigger: 'blur',
          },
          { min: 1, max: 500, message: '技术缺陷不超过500个字', trigger: 'blur' },
        ],
        publishUserName: [
          // {
          //   required: true,
          //   message: '请输入项目经理',
          //   trigger: 'blur',
          // },
        ],
        fileType: [
          {
            required: true,
            message: '请选择文件形式',
            trigger: 'blur',
          },
        ],
        techCategory: [
          {
            required: true,
            message: '请选择技术类别',
            trigger: 'blur',
          },
        ],
      },
      dicts: {
        flagDict: [
          { code: '1', name: '是' },
          { code: '0', name: '否' },
        ],
        levelDict: [
          { code: '一级', name: '一级' },
          { code: '二级', name: '二级' },
          { code: '三级', name: '三级' },
          { code: '四级', name: '四级' },
        ],
      },
      keyWordsNodesTree: [],
      fileTypeDic: [],
      techCategoryDic: [],
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractReportInfo',
      },
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },

      patent: {
        columns: [
          {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            width: 10,
            customRender: (text, record, index) => `${index + 1}`,
          },
          {
            title: '专利号',
            width: 100,
            scopedSlots: { customRender: 'patentCode' },
          },
          {
            title: '名称',
            width: 150,
            scopedSlots: { customRender: 'patentName' },
          },
          {
            title: '数量',
            width: 50,
            scopedSlots: { customRender: 'patentAmount' },
          },
          {
            title: '专利链接',
            width: 300,
            scopedSlots: { customRender: 'patentLink' },
          },
        ],
        currentSelection: [],
        selectedRowKeys: [],
        freshKey: 0,
      },
      coreFile: {
        fileList: [],
        colums: [
          {
            title: '附件名称',
            dataIndex: 'confidentialName',
            key: 'confidentialName',
          },
          {
            title: '附件大小',
            dataIndex: 'confidentialSizeText',
            key: 'confidentialSizeText',
          },
          {
            title: '上传时间',
            dataIndex: 'createTime',
            key: 'createTime',
          },
          {
            title: '上传者',
            dataIndex: 'uploader',
            key: 'uploader',
          },
        ],
        busField: 'techFileCore',
        busKey: '',
        busType: '',
        selectedRowKeys: [],
        currentSelection: [],
      },
      otherFile: {
        fileList: [],
        colums: [
          {
            title: '附件名称',
            dataIndex: 'name',
            scopedSlots: { customRender: 'name' },
          },
          {
            title: '附件大小',
            dataIndex: 'sizeText',
            key: 'sizeText',
          },
          {
            title: '上传时间',
            dataIndex: 'createTime',
            key: 'createTime',
          },
          {
            title: '上传者',
            dataIndex: 'uploader',
            key: 'uploader',
          },
        ],
        busField: 'techFileOthers',
        busKey: '',
        busType: '',
        selectedRowKeys: [],
        currentSelection: [],
      },
      urls: {
        keyWordsNodesTree: '/techKeyWords/nodesTree',
        downLoadBatch: '/common/downLoadBatch',
        coreFileUpload: '/fileCommon/attachmentCrypt',
        coreFileList: '/fileCommon/list',
        coreFileDelete: '/fileCommon/deleteCrypt',
        otherFileDelete: '/common/deleteBatch',
        otherFileDownload: '/common/downLoadBatch',
        generateUuid: '/common/generateUuid',
        save: '/rad/technology/save',
        submit: '/rad/technology/submit',
        queryById: '/rad/technology/queryById',
        getAttachs: '/tp/attach/getAttaches',
        delete: '/rad/technology/delete',
      },
      pushUserOriginTargetKeys: [],
      hasConfirmTechDegreeTest: false
    }
  },
  computed: {
    otherFileList() {
      var files = []
      this.otherFile.fileList.forEach((f) => {
        f.sizeText = formatFileSize(f.size)
        files.push(f)
      })
      console.info(files)
      return files
    },
    uploadHeaders() {
      /** upload headers */
      let headers = {
        busField: this.coreFile.busField,
        busKey: this.coreFile.busKey,
        busType: this.coreFile.busType,
      }
      headers['X-Access-Token'] = this.$ls.get(ACCESS_TOKEN)
      return headers
    },
    /** 上传请求地址 */
    uploadAction() {
      return window._CONFIG['domianURL'] + this.urls.coreFileUpload
    },

    editDisable() {
      return this.form.status && [0, 3].indexOf(this.form.status) <= -1
    },
    audit() {
      return [1].indexOf(this.form.status) > -1
    },
  },
  mounted() {
    this.initKeyWordsNodesTree()
    this.initDict('技术库-文件形式', 'fileTypeDic')
    this.initDict('技术库-技术类别（专业）', 'techCategoryDic')
    this.initDict('工程技术关键字对应等级', 'keyWordLevel')
    this.form.id = getParamValFromUrl('id')
    this.form.code = getParamValFromUrl('projectNo')
    this.messageId = getParamValFromUrl('messageId')
    this.initData()
  },
  methods: {
    filterHasPermission,
    initData() {
      if (strNotNull(this.form.id)) {
        getAction(this.urls.queryById, { id: this.form.id }).then((res) => {
          if (res.success) {
            this.form = res.result
            this.coreFile.busKey = this.form.id
            this.coreFile.busType = this.form.fileCode || this.form.fileNoShow
            this.otherFile.busKey = this.form.id
            this.otherFile.busType = this.form.fileCode || this.form.fileNoShow
            if (strNotNull(this.form.keyWord)) {
              this.$set(this.form, 'keyWordArr', this.form.keyWord.split(','))
            }
            this.freshCoreFileList()
            this.fetchAttach()
            this.fetchProcess(this.form.processInstanceId)
          } else {
            this.$message.warning('加载科技信息失败，请刷新页面:', res.message)
          }
        })
      } else {
        getAction(this.urls.generateUuid, {}).then((res) => {
          if (res.success) {
            this.form.id = res.result
          } else {
            this.$message.warning('获取数据id失败，请刷新页面:', res.message)
          }
        })
      }
    },
    selectPushUser() {
      this.pushUserOriginTargetKeys = strNotNull(this.form.publishUserId) ? this.form.publishUserId.split(',') : []
      this.$refs.userSelect.doSelect()
    },
    setPushUserName(result) {
      var usernames = []
      var realnames = []
      if (result != null) {
        result.forEach((item) => {
          usernames.push(item.username)
          realnames.push(item.realname)
        })
        this.form.publishUserId = usernames.join(',')
        this.form.publishUserName = realnames.join(',')
      }
    },
    setAuditUser(result) {
      if (result != null && result.length > 0) {
        this.form.auditUser = result[0].username
        postAction(this.urls.submit, this.form)
          .then((res) => {
            if (res.success) {
              this.$message.success('操作成功', 1)
              this.initData()
              if (this.$route.params.id) {
              } else {
                this.$router.push('techEngineeEdit?id=' + res.result.id)
              }
            } else {
              this.$message.warning('提交数据出错:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('提交数据异常:' + res.message)
          })
      } else {
        this.$message.warning('请选择第一岗审核人')
      }
    },
    initKeyWordsNodesTree() {
      postAction(this.urls.keyWordsNodesTree, { category: '2' }).then((res) => {
        if (res.success) {
          this.keyWordsNodesTree = res.result
        } else {
          this.$message.warning('加载关键字失败:', res.message)
        }
      })
    },
    initDict(type, variable) {
      getAction('/manage/codeInfo/list', { type: type, isdel: 0 })
        .then((res) => {
          if (res.code == 200) {
            this[variable] = res.result.records
          } else {
            this.$message.warning('字典初始化[' + type + ']失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('字典初始化[' + type + ']异常:' + res.message)
        })
    },
    handleChange(f) {
      var file = f.file
      if (file.status == 'done' && file.response != null) {
        if (file.response.code == 200) {
          this.$message.success('上传成功')
          this.freshCoreFileList()
        } else {
          this.$message.warning('上传失败:' + file.response.message)
        }
      }
    },
    freshCoreFileList() {
      getAction(this.urls.coreFileList, {
        busField: this.coreFile.busField,
        busKey: this.coreFile.busKey,
        busType: this.coreFile.busType,
      }).then((res) => {
        if (res.success) {
          this.coreFile.fileList = res.result
          this.coreFile.fileList.forEach((f) => (f.confidentialSizeText = formatFileSize(f.confidentialSize)))
        } else {
          this.$message.warning('加载文件列表出错:', res.message)
        }
      })
    },
    deleteCoreFile() {
      if (this.coreFile.selectedRowKeys.length < 1) {
        this.$message.warning('请选择要删除的核心文件')
        return
      }
      var currUser = Vue.ls.get(USER_INFO).username
      var fileNames = []
      this.coreFile.currentSelection.forEach((f) => {
        if (f.uploader != currUser) {
          fileNames.push(f.confidentialName)
        }
      })
      if (fileNames.length > 0) {
        this.$message.warning('核心文件区附件【' + fileNames.join(', ') + '】不是您上传的文件，不可删除')
        return
      }
      const that = this
      Modal.confirm({
        title: '确认删除',
        content: '此操作将删除选中的【核心文件】区域文件, 是否继续?',
        onOk: function () {
          var ids = that.coreFile.selectedRowKeys.join(',')
          getAction(that.urls.coreFileDelete, { ids: ids }).then((res) => {
            if (res.success) {
              that.$message.success('操作成功')
              that.freshCoreFileList()
            } else {
              that.$message.warning('加载文件列表出错:', res.message)
            }
          })
        },
      })
    },
    deleteOtherFile() {
      if (this.otherFile.selectedRowKeys.length < 1) {
        this.$message.warning('请选择要删除的【其它附件】区域文件')
        return
      }
      var currUser = Vue.ls.get(USER_INFO).username
      var fileNames = []
      this.otherFile.currentSelection.forEach((f) => {
        if (f.uploader != currUser) {
          fileNames.push(f.name)
        }
      })
      if (fileNames.length > 0) {
        this.$message.warning('核心文件区附件【' + fileNames.join(', ') + '】不是您上传的文件，不可删除')
        return
      }
      const that = this
      Modal.confirm({
        title: '确认删除',
        content: '此操作将删除选中的【其它附件】区域文件, 是否继续?',
        onOk: function () {
          var ids = that.otherFile.selectedRowKeys.join(',')
          getAction(that.urls.otherFileDelete, { attachIds: ids }).then((res) => {
            if (res.code == 1) {
              that.$message.success('操作成功')
              that.otherFile.selectedRowKeys.forEach((id) => {
                var index = that.otherFile.fileList.findIndex((attach) => {
                  return attach.id == id
                })
                if (index >= 0) {
                  console.log('index:', index)
                  that.otherFile.fileList.splice(index, 1)
                }
              })
            } else {
              that.$message.warning('删除附件失败:', res.msg)
            }
          })
        },
      })
    },
    showAttach(record) {
      var id = record.id
      var fileName = record.fileName
      //以rar、zip、dwg结尾的文件，直接下载不预览
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        this.doDownLoadBatch(id)
        return
      }
      let params = {
        id: id,
        ftpKey: 'ftp',
      }
      previewAttach(params)
        .then((result) => {
          const url = URL.createObjectURL(result)
          window.open(process.env.BASE_URL + '/pdf/web/viewer.html?file=' + url)
        })
        .catch((err) => {
          this.$message.warning('下载文件失败')
        })
    },
    doDownLoadBatch(attachIds, ftpKey = 'ftp') {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame')
      var href =
        this.API_BASE_URL +
        this.urls.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=' +
        ftpKey +
        '&token=' +
        this.$ls.get(ACCESS_TOKEN)
      iframe.src = href
    },
    handleSave(type) {
      this.form.techClass = '40'
      this.form.busType = type
      var checkFields = ['code', 'name']
      if (this.form.hadCode == '1') {
        if (!this.form.code) {
          this.$message.warning('请输入项目号')
          return
        }
      }
      for (let r in this.rules) {
        if (type == 'save' && checkFields.indexOf(r) == -1) {
          continue
        }
        if (r == 'code' && this.form.hadCode != '1') {
          continue
        }
        var rs = this.rules[r]
        var val = this.form[r]
        if (!strNotNull(val) && rs.length > 0 && rs[0].required) {
          this.$message.warning(rs[0].message)
          return
        }
        if (strNotNull(val) && rs.length > 1) {
          //校验长度
          let min = rs[1].min
          let max = rs[1].max
          let len = this.form[r].length
          if (len < min || len > max) {
            this.$message.warning(rs[1].message)
            return
          }
        }
      }
      if (this.form.patentList != null && this.form.patentList.length > 0) {
        for (var i = 0; i < this.form.patentList.length; i++) {
          if (this.form.patentList[i].name.trim() == '') {
            this.$message.warning('【技术知识产权-专利】第' + (i + 1) + '行名称不可为空')
            return
          }
        }
      }
      if (this.form.keyWordArr != null && this.form.keyWordArr.length > 0) {
        this.$set(this.form, 'keyWord', this.form.keyWordArr.join(','))
      }
      if (type == 'submit') {
        if (this.otherFileList == null || this.otherFileList.length <= 0) {
          this.$message.warning('请上传《技术等级测评表》附件后再提交！')
          return
        } else {
          let hasFile = false
          this.otherFileList.forEach((f) => {
            if (f.fileName.indexOf('技术等级测评表') > -1) {
              hasFile = true
            }
          })
          if (!hasFile) {
            this.$message.warning('请上传《技术等级测评表》附件后再提交！')
            return
          }
        }
        this.$refs.auditUserSelect.doSelect()
      } else {
        postAction(this.urls.save, this.form)
          .then((res) => {
            if (res.success) {
              this.$message.success('操作成功', 1)
              this.initData()
              if (this.$route.params.id) {
              } else {
                this.$router.push('techEngineeEdit?id=' + res.result.id)
              }
            } else {
              this.$message.warning('操作数据出错:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('操作数据异常:' + res.message)
          })
      }
    },
    onPatentSelectChange(selectedRowKeys, selectedRows) {
      this.patent.selectedRowKeys = selectedRowKeys
      this.patent.currentSelection = selectedRows
    },
    patentAdd() {
      this.form.patentList.push({
        id: Date.now() + this.form.patentList.length,
        code: '',
        name: '',
        amount: 0,
        link: '',
      })
    },
    patentRemove() {
      if (this.patent.selectedRowKeys.length == 0) {
        this.$message.warning('请选择要删除的技术知识产权-专利')
        return
      }
      var vm = this
      Modal.confirm({
        title: '警告',
        content: '真的要删除吗?',
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          // 在这里调用删除接口
          for (var i = 0; i < vm.patent.selectedRowKeys.length; i++) {
            for (var j = vm.form.patentList.length - 1; j >= 0; j--) {
              if (vm.form.patentList[j].id == vm.patent.selectedRowKeys[i]) {
                vm.form.patentList.splice(j, 1)
                break
              }
            }
          }
          vm.patent.selectedRowKeys = []
          vm.patent.currentSelection = []
          vm.patent.freshKey++
        },
        onCancel() {
          console.log('patentRemove Cancel')
        },
      })
    },
    onCorefileSelectChange(selectedRowKeys, selectedRows) {
      this.coreFile.selectedRowKeys = selectedRowKeys
      this.coreFile.currentSelection = selectedRows
    },
    onOtherfileSelectChange(selectedRowKeys, selectedRows) {
      this.otherFile.selectedRowKeys = selectedRowKeys
      this.otherFile.currentSelection = selectedRows
    },
    changeKeyWord() {
      let hasKeyWord = false
      let code = ''
      this.keyWordLevel.forEach((d) => {
        this.form.keyWordArr.forEach((k) => {
          if (k.indexOf(d.name) > -1) {
            code = d.code
            hasKeyWord = true
          }
        })
      })
      if (hasKeyWord) {
        this.$set(this.form, 'techLevel', this.dicts.levelDict[parseInt(code) - 1].name)
      }
    },
    openTechDegreeTest() {
      this.$refs.TechDegreeTest.init()
    },
    closeTechDegreeTest() {
      this.hasConfirmTechDegreeTest = true
    },
    downloadOtherFile() {
      if (!this.otherFile || !this.otherFile.selectedRowKeys || this.otherFile.selectedRowKeys <= 0) {
        return this.$message.warning('请最少选择一个文件下载')
      }
      const token = Vue.ls.get(ACCESS_TOKEN)
      let downloadUrl =
        process.env.VUE_APP_API_BASE_URL +
        '/common/downLoadBatchWithFileName?token=' +
        token +
        '&attachIds=' +
        this.otherFile.selectedRowKeys.join(',')
      window.open(downloadUrl)
    },
    afterUpload(response) {
      let record = {} //this.attachs[this.index]
      if (response && response.length > 0) {
        this.fetchAttach(this.otherFile)
      }
    },
    fetchAttach(obj) {
      if (this.busKey) {
        getAction(this.urls.getAttachs + '?busField=' + obj.busField + '&busKey=' + obj.busKey).then((res) => {
          if (res.code == '1') {
            this.obj.fileList = res.data
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },
    showTechEngineeFlowTips() {
      this.$refs.TechEngineeFlowTips.open()
    },
    openProjectSelector() {
      this.$refs.projectSelector.openInit({ projectClasses: ['40', '41'], withOutProjectSubTypes: ['S'] })
    },
    closeProjectSelector(project) {
      if (project) {
        this.$set(this.form, 'code', project.projectNo)
      }
    },
    handleDele() {
      let that = this
      Modal.confirm({
        title: '确认删除',
        content: '此操作将删除当前技术库?',
        onOk: function () {
          getAction(that.urls.delete, { id: that.form.id }).then((res) => {
            if (res.success) {
              that.$message.success('操作成功')
              window.close()
            } else {
              that.$message.warning('操作失败:', res.message)
            }
          })
        },
      })
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';

/deep/ .ant-form .ant-form-item:not(.self-form-item) .ant-form-item-label {
  width: 120px;
}

.mouldTips {
  border-radius: 5px;
  padding-left: 15px;
  font-size: 14px;
  font-weight: normal;
  color: #085082;
  line-height: 22px;
  display: inline-block;
}

.page-main {
  .container {
    .content {
      margin-top: 20px;

      section {
        .section-table {
          .add-btn {
            margin-left: 0;
            margin-bottom: 10px;
          }
        }
      }
    }
  }

  .tips-box {
    margin-top: 32px;

    .add-btn {
      width: 180px;
      height: 40px;
      line-height: 40px;
      background-color: #4095e4;
      border-radius: 2px;
    }
  }
}

.icon-file {
  background-image: url('../../../assets/file.png');
}

.cr-content-pop {
  p {
    margin-bottom: 15px;
    color: #666;

    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
